<script setup lang='ts'>
import { computed, h, nextTick, onMounted, ref, watch } from 'vue'
import { getLastBottomOffset, getLastInstance } from './method'
import type { MessageProps } from './types'

const visible = ref(false)
// withDefaults() 给props 添加默认值
const props = withDefaults(defineProps<MessageProps>(), {
  duration: 3000,
  type: 'message',
  offset: 20
})

// // 获取上一个组件实例
// const prev = getLastInstance()
// console.log(`prev`,prev);

// 1.计算div的高度
const height = ref(0)
const messageRef = ref<HTMLDivElement>()

// 2.上一个实例的最下面的坐标数字
const lastOffset = computed(() => getLastBottomOffset(props.id))

// 3. 该元素的top计算值
const topOffset = computed(() => lastOffset.value + props.offset)

// 4. 该元素为下一个元素预留的offset，也就是最底端的bottom的值
const bottomOffset = computed(() => height.value + topOffset.value)

const cssStyle = computed(() => ({
  top: topOffset.value + 'px'
}))
function startTimer() {
  if (props.duration === 0) return
  setTimeout(() => {
    visible.value = false
  }, props.duration)
}

onMounted(async () => {
  visible.value = true
  await nextTick()
  height.value = messageRef.value!.getBoundingClientRect().height
  startTimer()
})

watch(visible, (newValue) => {
  if (!newValue) {
    props.onDestroy()
  }
})

defineExpose({
  bottomOffset
})
</script>
<template>
  <div
    class="message-box"
    :style="cssStyle"
    :class="{ [`el-message--${type}`]: type }"
    ref="messageRef"
    v-show="visible"
  >
    <div class="message_content">
      <span> {{ message }}</span>
    </div>
    <img @click="visible = false" v-if="showClose" src="./images/close.png" alt="" />
  </div>
</template>
<style scoped>
</style>
